using System.Collections.Generic;
using System.Linq;
using TeachingManagementSystem.DAL;
using TeachingManagementSystem.Models;
using System;

namespace TeachingManagementSystem.BLL
{
    public class UserBLL
    {
        private DataContext _context;

        public UserBLL()
        {
            _context = new DataContext();
        }

        // 用户登录验证
        public User ValidateLogin(string username, string password)
        {
            try
            {
                return _context.Users.FirstOrDefault(u => u.Username == username && u.Password == password && u.IsActive);
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"数据库访问错误: {ex.Message}");
                // 抛出异常以便上层处理
                throw new Exception("数据库连接失败，请检查数据库服务是否正常运行。", ex);
            }
        }

        // 获取所有用户
        public List<User> GetAllUsers()
        {
            return _context.Users.ToList();
        }

        // 根据ID获取用户
        public User GetUserByID(int userID)
        {
            return _context.Users.FirstOrDefault(u => u.UserID == userID);
        }

        // 根据角色获取用户
        public List<User> GetUsersByRole(UserRole role)
        {
            return _context.Users.Where(u => u.Role == role).ToList();
        }

        // 根据ID列表批量获取用户（性能优化）
        public List<User> GetUsersByIDs(List<int> userIDs)
        {
            if (userIDs == null || userIDs.Count == 0)
                return new List<User>();
                
            return _context.Users.Where(u => userIDs.Contains(u.UserID)).ToList();
        }

        // 添加用户
        public void AddUser(User user)
        {
            // EF Core会自动处理ID自增
            user.CreatedDate = DateTime.Now;
            _context.Users.Add(user);
            _context.SaveChanges(); // 保存到数据库
        }

        // 更新用户
        public void UpdateUser(User user)
        {
            var existingUser = _context.Users.FirstOrDefault(u => u.UserID == user.UserID);
            if (existingUser != null)
            {
                existingUser.Username = user.Username;
                existingUser.FullName = user.FullName;
                existingUser.Email = user.Email;
                existingUser.Phone = user.Phone;
                existingUser.Role = user.Role;
                existingUser.IsActive = user.IsActive;
                // 只有在密码不为空时才更新密码
                if (!string.IsNullOrEmpty(user.Password))
                {
                    existingUser.Password = user.Password;
                }
                
                _context.SaveChanges(); // 保存到数据库
            }
        }

        // 删除用户
        public void DeleteUser(int userID)
        {
            var user = _context.Users.FirstOrDefault(u => u.UserID == userID);
            if (user != null)
            {
                _context.Users.Remove(user);
                _context.SaveChanges(); // 保存到数据库
            }
        }

        // 检查用户名是否已存在
        public bool IsUsernameExists(string username, int excludeUserID = 0)
        {
            return _context.Users.Any(u => u.Username == username && u.UserID != excludeUserID);
        }
    }
}